package com.ayuku.commons;

import java.util.logging.Logger;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;

/**
 * 
 * @author putu kusuma <putukn@gmail.com>
 *
 */
public abstract class FormDialogBasic extends org.eclipse.swt.widgets.Dialog {
	private Shell dialogShell;
	private Group grpData;
	private int formMode = AYConst.MODE_VIEW;
	private String formKey = null;
	protected Button btnDelete;
	protected Button btnCancel;
	protected Button btnEdit;
	protected Button btnSave;
	private Composite cmpButton;
	private String funcId;

	public String getFuncId() {
		return funcId;
	}

	public void setFuncId(String funcId) {
		this.funcId = funcId;
	}

	private Logger LOG = Logger.getLogger(FormDialogBasic.class.getName());

	public FormDialogBasic(Shell parent, int style, int mode) {
		super(parent, style);
		this.setFormMode(mode);
	}

	public void open() {
		try {

			Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.DIALOG_TRIM
					| SWT.APPLICATION_MODAL);
		

			FormLayout dialogShellLayout = new FormLayout();
			dialogShell.setLayout(dialogShellLayout);

			dialogShell.setSize(527, 358);
			dialogShell.setBackground(SWTResourceManager.getColor(171, 209, 252));
			dialogShell.layout();
		

			FormData composite1LData = new FormData();
			composite1LData.width = 307;
			composite1LData.height = 30;
			composite1LData.top =  new FormAttachment(0, 1000, 5);
			composite1LData.left =  new FormAttachment(0, 1000, 6);
			cmpButton = new Composite(dialogShell, SWT.NONE);
			FillLayout composite1Layout = new FillLayout(org.eclipse.swt.SWT.HORIZONTAL);
			cmpButton.setLayout(composite1Layout);

			cmpButton.setLayoutData(composite1LData);
			cmpButton.setBackground(SWTResourceManager.getColor(171, 209, 252));
			composite1Layout.spacing = 4;
			btnSave = new Button(cmpButton, SWT.PUSH | SWT.CENTER);
			btnSave.setImage(SWTResourceManager.getImage(FormDialogBasic.class, "/images/form/database_save.png"));
			btnSave.setAlignment(SWT.CENTER);
			btnSave.setToolTipText("Simpan data");
			btnSave.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnSave.setBackground(SWTResourceManager.getColor(171, 209, 252));
			btnSave.setText("Simpan");
			btnSave.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnSaveWidgetSelected(evt);
				}
			});
			btnEdit = new Button(cmpButton, SWT.PUSH | SWT.CENTER);
			btnEdit.setImage(SWTResourceManager.getImage(FormDialogBasic.class, "/images/form/database_edit.png"));
			btnEdit.setToolTipText("Edit data");
			btnEdit.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnEdit.setBackground(SWTResourceManager.getColor(171, 209, 252));
			btnEdit.setText("Ubah");
			btnEdit.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnEditWidgetSelected(evt);
				}
			});
			btnDelete = new Button(cmpButton, SWT.PUSH | SWT.CENTER);
			btnDelete.setImage(SWTResourceManager.getImage(FormDialogBasic.class, "/images/form/database_delete.png"));
			btnDelete.setToolTipText("Hapus data");
			btnDelete.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnDelete.setBackground(SWTResourceManager.getColor(171, 209, 252));
			btnDelete.setText("Hapus");
			btnDelete.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnDeleteWidgetSelected(evt);
				}
			});

			btnCancel = new Button(cmpButton, SWT.PUSH | SWT.CENTER);
			btnCancel.setToolTipText("Cancel / refresh");
			btnCancel.setImage(SWTResourceManager.getImage(FormDialogBasic.class, "/images/form/database_refresh.png"));
			btnCancel.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnCancel.setGrayed(true);
			btnCancel.setBackground(SWTResourceManager.getColor(171, 209, 252));
			btnCancel.setText("Cancel");
			btnCancel.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnCancelWidgetSelected(evt);
				}
			});

			grpData = new Group(dialogShell, SWT.NONE);

			FillLayout group1Layout = new FillLayout(
					org.eclipse.swt.SWT.HORIZONTAL);
			grpData.setLayout(group1Layout);

			FormData grpDataLData = new FormData();
			grpDataLData.width = 582;
			grpDataLData.height = 126;
			grpDataLData.left = new FormAttachment(0, 1000, 6);
			grpDataLData.right = new FormAttachment(1000, 1000, -8);
			grpDataLData.top = new FormAttachment(0, 1000, 47);
			grpDataLData.bottom = new FormAttachment(1000, 1000, -7);

			grpDataLData.width = 582;
			grpDataLData.height = 290;
			grpDataLData.left =  new FormAttachment(0, 1000, 6);
			grpDataLData.right =  new FormAttachment(1000, 1000, -8);
			grpDataLData.top =  new FormAttachment(0, 1000, 37);
			grpDataLData.bottom =  new FormAttachment(1000, 1000, -7);
			grpData.setLayoutData(grpDataLData);
			grpData.setBackground(SWTResourceManager.getColor(171, 209, 252));

			getPanelContent(grpData);

			additionalProses();

			// JANGAN DIBALIK URUTANNYA DENGAN ADITIONAL PROSES
			// MENGAKIBATKAN COMBO TIDAK BERFUNGSI
			loadData();

			dialogShell.setMinimumSize(360,160);
			dialogShell.open();
			Display display = dialogShell.getDisplay();

			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			LOG.info(e.getMessage());
			Util.showMsgBox("Gagal load: " + e.getMessage(), 2,
					getDialogShell());	
		}
	}

	protected final void loadData() {
		// LOAD DATA SESUAI KEY
		try {
			if (getFormMode() == AYConst.MODE_VIEW) {
				doLoad(getFormKey());

				// DISABLED KONTROL
				enabledControl(false, false);
				disabledAddButton(true);
			} else {
				doLoadAdd(null);
				// set form mode to new
				enabledControl(true, true);
				disabledAddButton(false);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOG.info(e.getMessage());
			Util.showMsgBox("Gagal load: " + e.getMessage(), 1,
					getDialogShell());				
		}
	}

	protected final void disabledAddButton(boolean enabled) {
		btnSave.setEnabled(!enabled);
		btnEdit.setEnabled(enabled);
		btnDelete.setEnabled(enabled);
		btnCancel.setEnabled(false);
		disabledOtherButton(enabled);
	}

	protected final boolean saveData() {
		if (!doValidate()) {
			return false;
		}

		if (getFormMode() == AYConst.MODE_ADD) {
			if (!doInsert()) {
				return false;
			}
		} else if (getFormMode() == AYConst.MODE_EDIT) {
			if (!doUpdate()) {
				return false;
			}
		}
		return true;
	}

	protected abstract int doMainInsert() throws Exception;

	protected abstract int doMainUpdate() throws Exception;

	protected abstract int doMainDelete() throws Exception;

	protected abstract void setPojoWithData() throws Exception;

	protected abstract void getPanelContent(Group grpData);

	protected abstract void additionalProses();

	protected abstract boolean doValidate();

	protected abstract void doLoad(String key) throws Exception;

	protected abstract void enabledControl(boolean otherfield, boolean key);

	protected abstract void clearContols();
	protected abstract void disabledOtherButton(boolean enable);
	protected abstract void doLoadAdd(String key) ;

	protected boolean doInsert() {
		boolean rtrValue = true;

		try {
			int n = doMainInsert();
			if (n < 1) {
				return false;
			}
			Util.OPERATION_CODE = 1;
		} catch (Exception e) {
			e.printStackTrace();
			
			if (e.getMessage()!=null && e.getMessage().contains("Duplicate")){
				Util.showMsgBox(AYConst.TRX_FAIL + ", karena kode/primary key sudah ada, silakan gunakan yang lain!",
						2, getDialogShell());	
			}else{
				Util.showMsgBox(AYConst.TRX_FAIL + ", karena: " + e.getMessage(),
					2, getDialogShell());
			}
			rtrValue = false;
		}

		return rtrValue;
	}

	protected boolean doUpdate() {
		boolean rtrValue = true;

		try {
			int n = doMainUpdate();
			if (n < 1) {
				return false;
			}
			Util.OPERATION_CODE = 2;
		} catch (Exception e) {
			e.printStackTrace();
			Util.showMsgBox(AYConst.TRX_FAIL + ", karena: " + e.getMessage(),
					2, getDialogShell());
			rtrValue = false;
		}

		return rtrValue;
	}

	protected boolean doDelete() {
		boolean rtrValue = true;

		MessageBox messageBox = new MessageBox(getDialogShell(), SWT.OK
				| SWT.CANCEL | SWT.ICON_WARNING);
		messageBox.setMessage(AYConst.CONFIRM_DELETE);

		if (messageBox.open() == SWT.OK) {
			try {
				doMainDelete();
				Util.OPERATION_CODE = 3;
				Util.showMsgBox(AYConst.TRX_SUCCESS, 0, getDialogShell());
				getDialogShell().dispose();
			} catch (Exception e) {
				e.printStackTrace();
				rtrValue = false;
				Util.showMsgBox(AYConst.TRX_FAIL + ", karena: "
						+ e.getMessage(), 2, getParent());
			}
		}

		return rtrValue;
	}

	private final void btnSaveWidgetSelected(SelectionEvent evt) {
		if (!saveData()) {
			return;
		}

		enabledControl(false, false);
		setFormMode(AYConst.MODE_VIEW);
		disabledAddButton(true);
		// hilangkan di bawah ini jika tidak mau langsung close
		dialogShell.close();

		//

	}

	private final void btnEditWidgetSelected(SelectionEvent evt) {
		if (!Util.isAllowedEdit(getFuncId())){
			Util.showMsgBox("Anda tidak mempunyai hak untuk edit data", 1, dialogShell);
			return;
		}
		editData();
	}

	private final void btnDeleteWidgetSelected(SelectionEvent evt) {
		if (!Util.isAllowedDelete(getFuncId())){
			Util.showMsgBox("Anda tidak mempunyai hak untuk hapus data", 1, dialogShell);
			return;
		}
		doDelete();
	}

	protected final String getFormKey() {
		return formKey;
	}

	public final void setFormKey(String key) {
		this.formKey = key;
	}

	protected final int getFormMode() {
		return formMode;
	}

	protected final void setFormMode(int frmMode) {
		this.formMode = frmMode;
	}

	protected final void editData() {
		disabledAddButton(false);
		enabledControl(true, false);
		btnCancel.setEnabled(true);
		setFormMode(AYConst.MODE_EDIT);
	}

	protected final void newData() {
		disabledAddButton(false);
		enabledControl(true, true);
		btnCancel.setEnabled(true);
		clearContols();
		setFormMode(AYConst.MODE_ADD);
	}

	protected Shell getDialogShell() {
		return dialogShell;
	}

	public Group getGrpData() {
		return grpData;
	}

	public void setGrpData(Group grpData) {
		this.grpData = grpData;
	}

	private void btnCancelWidgetSelected(SelectionEvent evt) {
		try {
			doLoad(getFormKey());
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info(e.getMessage());
			Util.showMsgBox("Gagal load: " + e.getMessage(), 1,
					getDialogShell());				
		}
		enabledControl(false, false);
		disabledAddButton(true);
		setFormMode(AYConst.MODE_VIEW);
	}

	public void exportToExcel() {
		// TODO Auto-generated method stub
		
	}

}
